#ifdef UDP_BROADCAST
//#include <EthernetUdp.h>
#define UDP_TX_PACKET_MAX_SIZE 80
EthernetUDP Udp;
IPAddress broadcastIP(192, 168, 0, 255);
char packetBuffer[UDP_TX_PACKET_MAX_SIZE]; //buffer to hold incoming packet,

/*********************************************************************************************\ 
 * Dit deel van de plugin wordt eenmalig aangeroepen direct na boot en tonen welkomsttekst
 \*********************************************************************************************/
void UserPlugin_UDP_Init(void)
{
  Udp.begin(514);
}

boolean UserPlugin_UDP_Receive(unsigned long Event)
{

  byte code=0;

  userPluginUDPPrintEvent(Event);

  // funktie kan op twee manieren worden verlaten:
  // true = Nodo gaat verder met verwerking van het event
  // false = Event wordt niet verder behandeld.
  if (code == 0) return true;
  return false;
}


void UserPlugin_UDP_Periodically()
{
  int packetSize = Udp.parsePacket();
  if(packetSize)
  {
    Serial.println("Received UDP packet");
    Udp.read(packetBuffer,UDP_TX_PACKET_MAX_SIZE);
    ExecuteLine(packetBuffer, VALUE_SOURCE_TELNET);
    Serial.println(packetBuffer);
  }

  return;
}

/*********************************************************************************************\
 * broadcast packet so syslog service can receive it
 \*********************************************************************************************/
void BroadcastUDP(char* LineToSend)
{
  Udp.beginPacket(broadcastIP, 514);
  Udp.write(LineToSend);
  Udp.endPacket();
}

/*********************************************************************************************\
 * copy of build-in printevent function, only to make the UDP Broadcast work for syslog messages
 \*********************************************************************************************/
#if NODO_MEGA
void userPluginUDPPrintEvent(unsigned long Content)
{

  byte x;

  // Commando(s) die NIET aan de gebruiker getoond hoeven te worden.
  switch((Content>>16)&0xff)// Cmd
  {
  case CMD_TRANSMIT_QUEUE:
    return;
  }

  char* StringToPrint=(char*)malloc(100);
  char* TmpStr=(char*)malloc(INPUT_BUFFER_SIZE+1);

  StringToPrint[0]=0; // als start een lege string

  x=true;

  // Unit
  if(((Content>>28)&0xf)==((unsigned long)(SIGNAL_TYPE_UNKNOWN)))  // Als het een onbekend type signaal is, dan unit niet weergeven.
    x=false;

  if(x)
  {
    //strcat(StringToPrint, ", "); 
    strcat(StringToPrint, cmd2str(CMD_UNIT));
    strcat(StringToPrint, "=");
    strcat(StringToPrint, int2str((Content>>24)&0xf)); 
  }

  // Event
  strcat(StringToPrint, ", ");
  strcat(StringToPrint, ProgmemString(Text_14));
  Event2str(Content,TmpStr);
  strcat(StringToPrint, TmpStr);

  if(((Content>>16)&0xff)==CMD_MESSAGE)
  {
    strcat(StringToPrint, " (");
    strcat(StringToPrint, cmd2str(Content&0xff));
    strcat(StringToPrint, ")");
  }

  BroadcastUDP(StringToPrint);

  free(TmpStr);
  free(StringToPrint);
}
#endif  // MEGA

#endif

